package com.lanzhou.yuanfen.util;


import com.lanzhou.yuanfen.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * 上传文件
 *
 * @author Administrator
 */
@Slf4j
@Component
public class UploadComponent {

    /**
     * 文件读取路径
     */
    @Resource
    private UploadProperties uploadProperties;

    /**
     * 上传代码
     *
     * @param fileUpload 上传文件
     * @param folder     新文件夹
     * @return 读取地址: 不包含下载ip地址
     */
    public String uploadFile(MultipartFile fileUpload, String folder) {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //指定本地文件夹存储图片
        String uploadUrl = uploadProperties.getUploadUrl();
        assert uploadUrl != null;
        long millis = System.currentTimeMillis();
        try {
            String targetFile = uploadUrl + (folder == null ? "" : folder + "/") + millis + suffixName;
            File downloadFile = new File(targetFile);
            if (!downloadFile.getParentFile().exists()) {
                boolean mkdirs = downloadFile.getParentFile().mkdirs();
                log.debug("创建文件夹结果为: [{}] ", mkdirs);
            }
            fileUpload.transferTo(downloadFile);
            // nginxPath为 Nginx挂载路径，这里的路径为："http://ip:9000/"
            log.info("上传成功, 上传文件新名字为: [ {} ]", millis + suffixName);
            return millis + suffixName;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败, 请检查相关配置和代码", e);
            return null;
        }
    }


}
